#!usr/bin/env python
# -*- coding:utf-8 _*-
"""
# author: 小菠萝测试笔记
# blog:  https://www.cnblogs.com/poloyy/
# time: 2021/10/12 6:53 下午
# file: deps.py
"""

from fastapi import Depends, HTTPException, status
from fastapi.security import OAuth2PasswordBearer
from jose import JWTError, jwt
from pydantic import ValidationError
from sqlalchemy.orm import Session

from app.config.setting import settings
from app.core.myenum import States
from app.core.security import ALGORITHM
from app.crud.crud_user import user
from app.db.session import SessionLocal
from app.models import User
from app.schemas.token import TokenPayload

reusable_oauth2 = OAuth2PasswordBearer(
    tokenUrl=f"{settings.api_v1_sre}/login/access_token"
)


def get_db():
    db = None
    try:
        db = SessionLocal()
        yield db
    finally:
        db.close()


def get_current_user(
    db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
) -> User:
    """
    获取当前用户
    :param db: 数据库对象
    :param token: 依赖项
    :return:
    """
    try:
        # 解密，拿到数据
        payload = jwt.decode(token, settings.secret_key, algorithms=ALGORITHM)
        # 转换为 Token Model
        token_data = TokenPayload(**payload)
    except (JWTError, ValidationError):
        # 解密失败就会抛出异常
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN, detail="Invalid tokens"
        )
    # 去数据库查 user
    user_data = user.get(db, id=token_data.sub)
    if not user_data:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="用户不存在")
    return user_data


def get_current_active_user(user_data: User = Depends(get_current_user)) -> User:
    """
    获取当前激活用户
    :param user_data: 依赖项，获取用户
    :return:
    """
    if user_data.state == States.NO_ACTIVE:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户未激活")
    if user_data.is_delete == States.IS_DELETE:
        raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="用户不存在")
    return user_data
